$(function(){
	$('#photos .photo input').change(function(){
		var currentPhotoBlock = $(this).parent(); 
		var currentPhotoValue = $(this).val();
		var lastPhotoBlock = $('#photos .photo:last');
		
		var countPhoto = $('#photos .photo input').length;
		var lastPhoto = $('#photos .photo input:last');

		// Build new file field
		var newPhotoBlock = currentPhotoBlock.clone(true);

		// Clean data
		newPhotoBlock.children('input').val('').removeAttr('id');
		
		// Build delete button
		var btnDelete = $('<img style="border: 0px; cursor: pointer;" src="' + IMAGE_URL + '/btnClose.png" />').click(function(){
			currentPhotoBlock.remove();
		});
		
		if (currentPhotoValue == '') $(this).remove();
		
		// If the last field is filled then add delete button
		if (lastPhoto.val() != '') {
			// Add delete button
			btnDelete.appendTo(currentPhotoBlock);

			// If the photo count < MAX_PHOTOS then add empty photo field 
			if (countPhoto < MAX_PHOTOS ) {
				// Add new photo field
				lastPhotoBlock.after(newPhotoBlock);
			}
		}
	});
});